package org.example.spring.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.Arrays;

@RestController
@RequestMapping("/request")
public class RequestController {
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        Arrays.stream(cookies).forEach(x -> {
            System.out.println(x.getName() + ":" + x.getValue());
        });
        return "获取cookie成功";
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("username","张三");
        return "设置session成功";
    }
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("username");
        return "获取Session成功:" + name;
    }
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        String name = (String) session.getAttribute("username");
        return "获取Session成功:" + name;
    }
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("username") String username){
        return "获取Session成功:" + username;
    }
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return userAgent;
    }
    @RequestMapping("/getHeader2")
    public String getHeader(@RequestHeader("User-Agent")String userAgent){
        return userAgent;
    }
}
